package cn.summit.shiro.start;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.Arrays;

/**
 * @author summit
 * @since 2020/12/19 9:48
 */
public class CustomerRealm extends AuthorizingRealm {

    /**
     * @see SimpleAccountRealm#doGetAuthorizationInfo(org.apache.shiro.subject.PrincipalCollection)
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String primaryPrincipal = (String) principals.getPrimaryPrincipal();

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRoles(Arrays.asList("admin","user"));
        info.addStringPermission("admin:*:01");
        return info;
    }

    /**
     * @param token
     * @return
     * @throws AuthenticationException
     * @see org.apache.shiro.realm.SimpleAccountRealm#doGetAuthenticationInfo
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
        throws AuthenticationException {
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        String username = upToken.getUsername();

        if (username.equals("summit")) {
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(username, "a18d2133f593d7b0e3ed488560404083",
                ByteSource.Util.bytes("salt"),
                this.getName());
            return info;
        }
        return null;
    }
}
